package com.cyk.controller;

import com.cyk.dubbo.api.UserService;
import io.netty.util.internal.StringUtil;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;

@RestController
@RequestMapping("/user")
public class UserController {
    @Reference
    private UserService userService;

    /*
    注册接⼝，true成功，false失败
     */
    @GetMapping("/register/{email}/{password}/{code}")
    public boolean register(@PathVariable String email, @PathVariable String password, @PathVariable String code) {
        return userService.register(email, password, code);
    }

    /*
    是否已注册，根据邮箱判断,true代表已经注册过， false代表尚未注册
     */
    @GetMapping("/isRegistered/{email}")
    public boolean isRegistered(@PathVariable String email) {
        return userService.isRegistered(email);
    }

    /*
    登录接⼝，验证⽤用户名密码合法性，
    根据⽤用户名和 密码⽣生成token，
    token存⼊入数据库，并写⼊入cookie 中，
    登录成功返回邮箱地址，重定向到欢迎⻚页
     */
    @GetMapping("/login/{email}/{password}")
    public String login(HttpServletResponse response, @PathVariable String email, @PathVariable String password) {
        String token = userService.login(email, password);
        if (!StringUtil.isNullOrEmpty(token)) {
            response.addCookie(new Cookie("token", token));
        }
        return token;
    }

    @GetMapping("/info/{token}")
    public String info(@PathVariable String token) {
        return userService.info(token);
    }
}
